package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.entity.YddTag;
import com.itheima.ydd.service.YddCateService;
import com.itheima.ydd.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ydd_cate")
@Slf4j
public class YddCateController {
    @Autowired
    private YddCateService yddCateService;

    @GetMapping("/list")
    public R getList(String catename, int page, int limit) {
        log.info("查询参数{}", catename, page, limit);
        //构造分页构造器对象
        Page<YddCate> catePage = new Page<>(page, limit);

        //构造查询条件
        LambdaQueryWrapper<YddCate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(catename), YddCate::getCatename, catename);
        queryWrapper.orderByAsc(YddCate::getSortNum);
        //执行分页查询
        yddCateService.page(catePage, queryWrapper);

        List<YddCate> records = catePage.getRecords();
        long total = catePage.getTotal();

        PageUtils<YddCate> init = new PageUtils<>(catePage);
        return R.success("", init);
    }

    @GetMapping("/rowInfo")
    public R rowInfo(Integer id) {
        log.info("id: {}", id);
        YddCate byId = yddCateService.getById(id);
        return R.success("", byId);
    }

    @PostMapping("/update")
    public R updateByYddAdvpos(@RequestBody YddCate yddCate) {
        log.info("yddCate: {}", yddCate);
        yddCateService.updateById(yddCate);
        return R.success("修改成功", "");
    }

    @PostMapping("/add")
    public R addByYddAdvpos(@RequestBody YddCate yddCate) {
        log.info("yddCate: {}", yddCate);
        yddCateService.save(yddCate);
        return R.success("添加成功", "");
    }

    @GetMapping("/del")
    public R deleteByYddCate(Integer id) {
        log.info("id: {}", id);
        //判断DefaultData是否为1，如果为默认值1则不能删除
        YddCate byId = yddCateService.getById(id);
        if (byId.getDefaultData() != null && byId.getDefaultData().equals("1")) {
            return R.error("不能删除");
        }
        yddCateService.removeById(id);
        return R.success("删除成功", "");
    }

    /**
     *标签列表---全部
     *
     * @return
     */
    @GetMapping("/all")
    public R all(){
        List<YddCate> list = yddCateService.list();
        return R.success("",list);
    }

}
